package com.aqiang.day0528_shop.user.view.activity

import android.app.Notification
import android.app.NotificationManager
import android.content.Context
import android.graphics.Color
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.View
import android.widget.RelativeLayout
import cn.sharesdk.framework.Platform
import cn.sharesdk.framework.PlatformActionListener
import cn.sharesdk.framework.ShareSDK
import cn.sharesdk.tencent.qq.QQ
import com.aqiang.day0528_shop.MainActivity
import com.aqiang.day0528_shop.R
import com.aqiang.day0528_shop.user.contract.UserContract
import com.aqiang.day0528_shop.user.entity.UserEntity
import com.aqiang.day0528_shop.user.presenter.LoginPresenter
import com.aqiang.lib_core.common.SLog
import com.aqiang.lib_core.mvp.BaseActivity
import com.zy.shopproject2.usercenter.entity.BaseResponseEntity
import kotlinx.android.synthetic.main.activity_login.*
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.toast
import java.util.*
import java.util.regex.Pattern
import kotlin.concurrent.timerTask

class LoginActivity : BaseActivity<UserContract.LoginPresenter>(),UserContract.LoginView {
    private var first:Int = 0
    private var time:Int = 60
    private var auth:Int = 0
    override fun bindLatout(): Int {
        return R.layout.activity_login
    }

    override fun createPresenter() {
        mPresenter = LoginPresenter(this)
    }

    override fun initView(savedInstanceState: Bundle?) {

    }

    override fun initData() {
        merge(R.id.tv_act_login_auth)
    }

    override fun initEvent() {
        iv_act_login_qq.setOnClickListener {
            val plat = ShareSDK.getPlatform(QQ.NAME)
//移除授权状态和本地缓存，下次授权会重新授权
            plat.removeAccount(true)
//SSO授权，传false默认是客户端授权
            plat.SSOSetting(false)
//授权回调监听，监听oncomplete，onerror，oncancel三种状态
            plat.platformActionListener = object : PlatformActionListener{
                override fun onComplete(p0: Platform?, p1: Int, p2: HashMap<String, Any>?) {
                    //toast("完成")
                    startActivity<MainActivity>()
                }

                override fun onCancel(p0: Platform?, p1: Int) {
                    //toast("取消")
                }

                override fun onError(p0: Platform?, p1: Int, p2: Throwable?) {
                    //toast("错误")
                }

            }
//抖音登录适配安卓9.0
//ShareSDK.setActivity(MainActivity.this)
//要数据不要功能，主要体现在不会重复出现授权界面
            plat.showUser(null)
        }
       bt_frag_auth_getauth.setOnClickListener {
           val timer = Timer()
           bt_frag_auth_getauth.isEnabled = false
           timer.schedule(timerTask {
               runOnUiThread {
                   bt_frag_auth_getauth.text = "重新发送${time}"
               }
               time--
               if(time <= 0){
                   timer.cancel()
                   runOnUiThread {
                       bt_frag_auth_getauth.text = "重新发送"
                       bt_frag_auth_getauth.isEnabled = true
                   }
               }
           },0,1000)
           doAsynTask {
               mPresenter!!.auth()
           }
       }
        tv_act_login_register.setOnClickListener {
            startActivity<RegisterActivity>()
        }
        tv_act_login_auth.setOnClickListener { v ->
            merge(R.id.tv_act_login_auth)
        }
        tv_act_login_pwd.setOnClickListener { v ->
            merge(R.id.tv_act_login_pwd)
        }
    }

    fun merge(id: Int){
        if(id == first){
            return
        }
        changeColor(id)
        first = id
    }

    fun changeColor(id:Int){
        if(id == R.id.tv_act_login_auth){
            tv_act_login_auth.setTextColor(Color.BLUE)
            in_dd.visibility = RelativeLayout.VISIBLE
            in_ff.visibility = RelativeLayout.GONE
            tv_act_login_pwd.setTextColor(Color.GRAY)
            bt_act_login.setOnClickListener { v ->
                doAsynTask {
                    var userReg:String = "^[1]\\d{10}$"
                    if (!Pattern.matches(userReg,getUser()) && getUser().isEmpty()){
                        launch {
                            withContext(Dispatchers.Main){
                                toast("不能为空或者手机格式不对")
                            }
                        }
                        return@doAsynTask
                    }
                    if(getAuth() != auth.toString()){
                        launch {
                            withContext(Dispatchers.Main){
                                toast("验证码不对")
                            }
                        }
                        return@doAsynTask
                    }
                    mPresenter!!.authLogin()
                }
            }
        }else{
            in_dd.visibility = RelativeLayout.GONE
            in_ff.visibility = RelativeLayout.VISIBLE
            tv_act_login_pwd.setTextColor(Color.BLUE)
            tv_act_login_auth.setTextColor(Color.GRAY)
            bt_act_login.setOnClickListener { v ->
                doAsynTask {
                    var userReg:String = "^[1]\\d{10}$"
                    if (!Pattern.matches(userReg,getUser()) && getUser().isEmpty()){
                        launch {
                            withContext(Dispatchers.Main){
                                toast("不能为空或者手机格式不对")
                            }
                        }
                        return@doAsynTask
                    }

                    mPresenter!!.login()
                }
            }
        }
    }

    override fun getUser(): String {
        return et_frag_auth_user.text.toString()
    }

    override fun getPwd(): String {
        return in_ff.text.toString()
    }

    override fun getAuth(): String {
        return et_frag_auth_auth.text.toString()
    }

    override fun successAuth(auth: Deferred<Int>) {
        doUiThread(auth,{
            this.auth = it
            val build = Notification.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("验证码")
                .setContentText("${it}")
                .build()
            val systemService = this.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            systemService.notify(1,build)
        })
    }
    override fun success(d: Deferred<BaseResponseEntity>) {
        doUiThread(d){
            if(it.code == 200){
                startActivity<MainActivity>()
                finish()
            }else{
                toast("密码不正确或者账号不正确")
                return@doUiThread
            }
        }
    }
}
